<template>
    <div class="">
        <!-- 商品(Spu)介绍 -->
        <el-card class="box-card">
            <div style="margin-bottom:20px">
                <span style="font-weight:700;">商品(Spu)介绍</span>
            </div>
            <div>
                <el-form ref="ruleFormRef" :model="productForm" :rules="productRules" label-width="120px">
                    <el-form-item label="商品名称" prop="title">
                        <el-input v-model="productForm.title" placeholder="请输入商品名称" clearable />
                    </el-form-item>
                    <el-form-item label="原始价格" prop="originalPrice">
                        <el-input v-model="productForm.originalPrice" placeholder="请输入原始价格" clearable>
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="当前价格" prop="price">
                        <el-input v-model="productForm.price" placeholder="请输入当前价格" clearable>
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="VIP价格" prop="vipPrice">
                        <el-input v-model="productForm.vipPrice" placeholder="请输入vip价格" clearable>
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="剩余库存">
                        <el-input v-model="productForm.sales" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="运费模板">
                        <el-select v-model="productForm.freightTemplateId" class="m-2" placeholder="请选择运费模板">
                            <el-option v-for="item in freight" :key="item.id" :label="item.title" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否在售" prop="status">
                        <el-radio-group v-model="productForm.status">
                            <el-radio :label="0">下架</el-radio>
                            <el-radio :label="1">在售</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品图片">
                        <el-upload :action="uploadAddr" :headers="headers" list-type="picture-card" :limit="5"
                            v-model:file-list="productForm.imgList" :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove" :on-exceed="handleMoreLimit">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品单位" prop="unit">
                        <el-input v-model="productForm.unit" placeholder="请输入商品单位" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="所属类目">
                        <el-cascader :options="options" v-model="productForm.categoryId"
                            :props="{ emitPath: false, value: 'id', label: 'title', children: 'childrenList' }"
                            placeholder="关联至类目" filterable clearable />
                    </el-form-item>
                    <el-form-item label="商品简介" prop="description">
                        <el-input v-model="productForm.description" placeholder="请输入商品简介" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="商品详细介绍" prop="detail">
                        <RichText v-model="productForm.detail" style="width:100%"></RichText>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <!-- 商品参数 -->
        <el-card>
            <div style="margin-bottom:20px">
                <span style="font-weight:700;display: block;margin-bottom: 10px;">商品参数</span>
                <el-button type="primary" plain @click="pruductAttrDialog = true">添加</el-button>
            </div>
            <div>
                <el-table :data="productForm.attributeList" style="width: 100%">
                    <el-table-column prop="attribute" label="商品参数名称" align="center" />
                    <el-table-column prop="value" label="商品参数值" align="center" />
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button type="danger" @click="handleDelProductAttr(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 商品参数对话框 -->
            <el-dialog v-model="pruductAttrDialog" title="添加商品参数" @close="handleCloseAttrDialog">
                <el-form ref="productRuleFormRef" :model="attrRuleForm" :rules="attrRules" label-width="120px">
                    <el-form-item label="商品参数名称" prop="attribute">
                        <el-input v-model="attrRuleForm.attribute" />
                    </el-form-item>
                    <el-form-item label="商品参数值" prop="value">
                        <el-input v-model="attrRuleForm.value" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitAttrForm(productRuleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetAttrForm(productRuleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

        </el-card>
        <!-- 规格维度 -->
        <el-card>
            <div style="margin-bottom:20px">
                <span style="font-weight:700;display: block;margin-bottom: 10px;">规格维度</span>
                <el-button type="primary" plain @click="handleAddSizeForm">添加</el-button>
            </div>
            <div>
                <el-table :data="productForm.specificationList" style="width: 100%">
                    <el-table-column prop="id" label="维度ID" align="center" />
                    <el-table-column prop="title" label="维度名称" align="center" />
                    <el-table-column label="创建时间" align="center">
                        <template #default="scope">
                            {{ friendTime(scope.row.gmtCreate) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button type="primary" @click="handleEditSize(scope.$index, scope.row)">修改</el-button>
                            <el-button type="danger" @click="handleDelSizeAttr(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 规格维度对话框 -->
            <el-dialog v-model="pruductSizeDialog" title="添加规格维度" @close="handleCloseSizeDialog">
                <el-form ref="sizeRuleFormRef" :model="sizeRuleForm" :rules="sizeRules" label-width="120px">
                    <el-form-item label="规格名称" prop="title">
                        <el-input v-model.trim="sizeRuleForm.title" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitSizeForm(sizeRuleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetSizeForm(sizeRuleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-card>
        <!-- 商品(Sku)详情 -->
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span style="font-weight:bold">商品(Sku)详情</span>
                    <div style="margin:10px;">
                        <el-button type="primary" plain @click="priceDialog = true"
                            :disabled="!productForm.skuList.length">批量定价</el-button>
                    </div>
                </div>
            </template>
            <div>
                <!-- sku的tag标签 -->
                <div v-for="item, index in productForm.specificationList" :key="item.gmtCreate" class="tag">
                    <el-tag type="warning">{{ item.title }}</el-tag>
                    <el-tag v-for="tag, tagIndex in item.children" :key="tag" class="mx-1" closable
                        :disable-transitions="false" @close="handleClose(index, tagIndex)">
                        {{ tag }}
                    </el-tag>
                    <el-input v-focus v-if="item.inputVisible" v-model="inputValue" class="ml-1 w-20" size="small"
                        @keyup.enter="handleInputConfirm(index)" @blur="handleInputConfirm(index)" />
                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(index)">
                        + 添加
                    </el-button>
                </div>
                <!-- sku表格 -->
                <div>
                    <el-table :data="productForm.skuList" border style="width: 100%" :span-method="handleSpanMethod">
                        <el-table-column v-for="item in productForm.specificationList.filter(item => item.children.length)"
                            :label="item.title" :prop="'id_' + item.title" />
                        <el-table-column prop="id" label="skuID" />
                        <el-table-column prop="price" label="价格(元)" width="180">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.price" :min="0" @change="handleJudgePrice(scope.row)"
                                    @focus="handleRenew(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="vipPrice" label="VIP价(元)" width="180">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.vipPrice" :min="0" @change="handleJudgePrice(scope.row)"
                                    @focus="handleRenew(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="originalPrice" label="吊牌价(元)" width="180">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.originalPrice" :min="0"
                                    @change="handleJudgePrice(scope.row)" @focus="handleRenew(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="库存(件)" width="180">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.stock" :min="0" />
                            </template>
                        </el-table-column>
                        <el-table-column label="重量(克)" width="180">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.weight" :min="0" />
                            </template>
                        </el-table-column>
                        <el-table-column label="SKU图片" align="center" width="150">
                            <template #default="scope">
                                <el-upload :action="uploadAddr" :headers="headers" :show-file-list="false"
                                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                                    <img v-if="scope.row.img" :src="scope.row.img" class="avatar"
                                        style="width:50px;height:50px;" />
                                    <el-icon :size="25" @click="imgIndex = scope.$index" v-else>
                                        <Upload />
                                    </el-icon>
                                </el-upload>
                            </template>
                        </el-table-column>
                        <el-table-column label="条形码" width="200">
                            <template #default="scope">
                                <el-input v-model="scope.row.barCode" disabled>
                                    <template #append>
                                        <el-button @click="handleRandomBarCode(scope.$index)">随机</el-button>
                                    </template>
                                </el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <!-- 批量定价对话框 -->
            <el-dialog v-model="priceDialog" title="批量定价" width="40%" @close="handleColseBatchDialog">
                <el-form ref="skuBatchRuleFormRef" :model="skuBatchForm" :rules="skuBatchRules" label-width="120px">
                    <el-form-item label="现价(￥)" prop="price">
                        <el-input-number v-model="skuBatchForm.price" :min="0" />
                    </el-form-item>
                    <el-form-item label="VIP价格(￥)" prop="vipPrice">
                        <el-input-number v-model="skuBatchForm.vipPrice" :min="0" />
                    </el-form-item>
                    <el-form-item label="吊牌价(￥)" prop="originalPrice">
                        <el-input-number v-model="skuBatchForm.originalPrice" :min="0" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="skuBatchSubmitForm(skuBatchRuleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="skuBatchResetForm(skuBatchRuleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <div class="saveBtn">
                <el-button @click="submitProductForm(ruleFormRef)" type="primary">保存</el-button>
            </div>
        </el-card>
        <!-- 跳转页面对话框 -->
        <el-dialog v-model="dialogTableVisible" title="是否跳转页面">
            <span>商品添加成功！！是否继续创建？</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleGoProduct">返回</el-button>
                    <el-button type="primary" @click="handleContinueCreate">
                        继续创建
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ClassProduct, ClassSku } from '#/index';
import RichText from '@/components/richtext/RichText.vue';
import { post, host } from '@/utils/http';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { computed, onMounted, reactive, ref, type Directive } from 'vue';
import { Plus, Upload } from '@element-plus/icons-vue';
import cookies from 'js-cookie'
import type { UploadProps } from 'element-plus'
import { friendTime } from '@/utils/DateFormatter';
import { useRouter } from 'vue-router';
import { useTagsStore } from '@/stores/tag/index'
import { initObj } from '@/utils';

/**使用自定义指令实现input框自动聚焦 */
const vFocus: Directive = {
    mounted(el: HTMLElement) {
        el.querySelector("input")?.focus();
    },
};
const router = useRouter()
const inputValue = ref('')
const dialogTableVisible = ref(false)

// 运费模板
const freight = ref()
//文件上传地址
const uploadAddr = host + '/upload/admin'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
//类目数据
const options = ref()
//文件上传请求头
const headers = computed(() => {
    return {
        ADMINTOKEN: cookies.get("adminToken")
    }
})
//form表单节点
const ruleFormRef = ref<FormInstance>()
//产品表单对象
const productForm = reactive({
    ...new ClassProduct(),
    imgList: [],
    detail: '',
    attributeList: [] as Array<{ attribute: string, value: string }>,
    specificationList: [] as Array<TypeSizeRuleForm>,
    skuList: [] as Array<ClassSku>,
    stock: 0
})
//商品参数form对象
const attrRuleForm = reactive({
    attribute: '',
    value: ''
})
const attrRules = reactive<FormRules>({
    attribute: [{ required: true, message: '请输入商品参数名称', trigger: 'blur' }],
    value: [{ required: true, message: '请输入商品参数名称', trigger: 'blur' }],
})
const productRuleFormRef = ref<FormInstance>()
//商品参数对话框
const pruductAttrDialog = ref(false)
//产品表单规则
const productRules = reactive<FormRules>({
    title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    originalPrice: [{ required: true, pattern: /^[1-9]\d*(.\d+)?$/, message: '请输入正确的格式', trigger: 'blur' }],
    price: [{ required: true, pattern: /^[1-9]\d*(.\d+)?$/, message: '请输入原始价格', trigger: 'blur' }],
    vipPrice: [{ required: true, pattern: /^[1-9]\d*(.\d+)?$/, message: '请输入VIP价格', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    unit: [{ required: true, message: '请输入商品单位', trigger: 'blur' }],
    description: [{ required: true, message: '请输入商品简介', trigger: 'blur' }],
})
const pruductSizeDialog = ref(false)
let tempSizeFormIndex = 0
const sizeRuleFormRef = ref<FormInstance>()
const sizeRuleForm = reactive({
    title: '',
    id: undefined,
    spuId: undefined,
    gmtCreate: 0,
    gmtUpdate: 0,
    name: '',
    children: [],
    inputVisible: false
})

const sizeRules = ref<FormRules>({
    title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
})
const imgIndex = ref(0)
const priceDialog = ref(false)
const skuBatchForm = reactive({
    price: 0,
    vipPrice: 0,
    originalPrice: 0
})
const skuBatchRules = reactive<FormRules>({
    price: [{ required: true, message: 'Please input Activity name', trigger: 'blur' }],
    vipPrice: [{ required: true, message: 'Please input Activity name', trigger: 'blur' }],
    originalPrice: [{ required: true, message: 'Please input Activity name', trigger: 'blur' }],
})
const skuBatchRuleFormRef = ref<FormInstance>()
/**
 * 生命周期获取数据
 */
onMounted(() => {
    getFreightList()
    getCategory()
})
/**
 * 获取运费模板数据
 */
function getFreightList() {
    const data = { _gp: 'admin.freight', _mt: 'list' }
    post(data).then(res => {
        const { data, errmsg, errno } = res
        if (200 == errno) {
            freight.value = data
        } else {
            ElMessage.error(errmsg)
        }
    })
}
/**
 * 获取分类树
 */
function getCategory() {
    const data = { _gp: 'admin.category', _mt: 'categoryTree' }
    post(data).then(res => {
        const { data, errno } = res
        if (200 === errno) {
            options.value = filterData(data)
        } else {
            ElMessage.error('获取分类失败')
        }
    })
}
/**
 * 过滤树数据，不能选择第二层
 * @param arr 数组
 */
function filterData(arr: []) {
    arr.forEach((item: any) => {
        if (item.childrenList) {
            filterData(item.childrenList)
        } else {
            if (item.level < 2) {
                item.disabled = true
            }
        }
    })
    return arr
}
/**
 * 删除图片
 */
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
/**
 * 查看图片
 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
/**
 * 图片上传限制提示
 */
function handleMoreLimit() {
    ElMessage.error('最多只能上传5张图片')
}
/**
 * 提交商品属性
 * @param formEl 
 */
const submitAttrForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            productForm.attributeList.unshift(Object.assign({}, attrRuleForm))

            pruductAttrDialog.value = false
        } else {
            console.log('error submit!', fields)
        }
    })
}
/**
 * 取消商品属性
 * @param formEl 
 */
const resetAttrForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    pruductAttrDialog.value = false
}
/**
 * 关闭商品属性对话框
 */
function handleCloseAttrDialog() {
    attrRuleForm.attribute = ""
    attrRuleForm.value = ""
    resetAttrForm(productRuleFormRef.value)
}
/**
 * 删除商品属性
 * @param row 当前行
 */
function handleDelProductAttr(row: { attribute: string, value: string }) {
    ElMessageBox.confirm(
        '是否删除该数据?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        let index = productForm.attributeList.findIndex(item => item.attribute === row.attribute && item.value === row.value)
        if (index != -1) {
            productForm.attributeList.splice(index, 1)
            ElMessage.success('删除成功')
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })

}
/**
 * 删除商品维度
 * @param index 
 */
function handleDelSizeAttr(index: number) {
    ElMessageBox.confirm(
        '是否删除该数据?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        productForm.specificationList.splice(index, 1)
        ElMessage.success('删除成功')
        createSkuTable()
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })

}
/**
 * 提交规格对话框
 * @param formEl 
 */
const submitSizeForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(sizeRuleForm)
            let index = productForm.specificationList.findIndex(item => item.title === sizeRuleForm.title)
            if (index == -1) {
                if (sizeRuleForm.name === "添加") {
                    sizeRuleForm.gmtCreate = new Date().getTime()
                    productForm.specificationList.unshift(Object.assign({}, { ...sizeRuleForm, children: [] }))
                } else {
                    productForm.specificationList[tempSizeFormIndex].title = sizeRuleForm.title
                    createSkuTable()
                    // ElMessage.error('该功能暂未完成')
                }
                pruductSizeDialog.value = false
            } else {
                ElMessage.error('该规格已存在')
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
/**
 * 取消规格对话框
 * @param formEl 
 */
const resetSizeForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    pruductSizeDialog.value = false
}
/**
 * 关闭规格对话框，清空数据
 */
function handleCloseSizeDialog() {
    sizeRuleFormRef.value?.resetFields()
    sizeRuleForm.gmtCreate = 0
    sizeRuleForm.name = ''
    sizeRuleForm.title = ''
}
/**
 * 打开编辑对话框
 * @param index 
 * @param row 
 */
function handleEditSize(index: number, row: TypeSizeRuleForm) {
    tempSizeFormIndex = index
    Object.assign(sizeRuleForm, row)
    sizeRuleForm.name = '修改'
    pruductSizeDialog.value = true
}
/**
 * 打开规格对话框
 */
function handleAddSizeForm() {
    sizeRuleForm.name = '添加'
    pruductSizeDialog.value = true
}
/**
 * 生成sku表格数据
 */
function createSkuTable() {
    //获取title数组
    let titleList = productForm.specificationList.filter(item => item.children.length > 0).map(item => {
        return item.title
    })
    let arr = productForm.specificationList.filter(item => item.children.length > 0).map(item => {
        return [...item.children]
    })
    if (arr.length === 0) {
        productForm.skuList = []
        return
    }
    //通过笛卡尔积获取sku
    let skulist = arr.reduce((total: string[][], current) => {
        let tempArr: string[][] = []
        total.forEach(element => {
            current.forEach(data => {
                tempArr.push(element.concat([data]))
            })
        });
        return tempArr
    }, [[]])
    console.log('skulist:', skulist)
    // const { price, vipPrice, originalPrice } = skuBatchForm
    var skuTable = skulist.map(item => {
        let obj = {
            price: undefined,
            vipPrice: undefined,
            originalPrice: undefined,
            stock: undefined,
            barCode: "",
            weight: undefined,
            img: "",
            titleArray: [] as string[],
            specificationArray: [] as string[],
            title: "",
            specification: "",
        };
        item.forEach((val: string, index: number) => {
            var key = "id_" + titleList[index]
            obj[key] = val
            obj.titleArray.push(val)
            obj.specificationArray.push(titleList[index] + "_" + val)
        })
        obj.title = obj.titleArray.join(',')
        obj.specification = obj.specificationArray.join(',')
        let findItem = productForm.skuList.find(item => item.specification === obj.specification)
        if (findItem) {
            return findItem
        }
        let skuObj = new ClassSku()
        Object.assign(skuObj, obj)
        return skuObj
    })
    console.log(skuTable)
    productForm.skuList = skuTable
}
/**
 * 上传图片成功后处理
 * @param response 
 * @param uploadFile 
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    productForm.skuList[imgIndex.value].img = response.url
}
/**
 * 上传图片前校验
 * @param rawFile 
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('上传的文件必须是jpg格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
/**
 * 生成条形码
 * @param index 当前行对应的数组index
 */
function handleRandomBarCode(index: number) {
    productForm.skuList[index].barCode = new Date().getTime() + ''
}
/**
 * 确定批量定价
 * @param formEl 
 */
const skuBatchSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const { price, vipPrice, originalPrice } = skuBatchForm
            if (vipPrice <= price && price <= originalPrice) {
                productForm.skuList.forEach(item => {
                    item.price = price
                    item.vipPrice = vipPrice
                    item.originalPrice = originalPrice
                })
                ElMessage.success('批量成功')
                priceDialog.value = false
            } else {
                ElMessage.error('价格应为：vip价<=现价<=原价')
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
/**
 * 
 * 取消批量定价
 */
const skuBatchResetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
/**
 * 关闭批量定价对话框
 */
function handleColseBatchDialog() {
    skuBatchRuleFormRef.value?.resetFields()
    skuBatchForm.originalPrice = 0
    skuBatchForm.vipPrice = 0
    skuBatchForm.price = 0
}
/**
 * 比较价格格式是否正常
 * @param row 当前行对象
 */
function handleJudgePrice(row: ClassSku) {
    let { price, originalPrice, vipPrice } = row
    if (vipPrice > price || price > originalPrice) {
        ElMessage.error('价格应为：vip价<=现价<=原价')
        Object.assign(row, tempPrice)
    }

    console.log(row)
}
//临时存储价格对象
const tempPrice = { price: 0, originalPrice: 0, vipPrice: 0 }
/**
 * 文本框获取焦点时保存到临时价格中
 * @param row 当前行对象
 */
function handleRenew(row: ClassSku) {
    tempPrice.price = row.price
    tempPrice.vipPrice = row.vipPrice
    tempPrice.originalPrice = row.originalPrice
}
/**
 * 合并单元格处理
 * 
 */
function handleSpanMethod({ rowIndex, columnIndex }: { rowIndex: number, columnIndex: number }) {
    // 过滤出规格列表中孩子长度大于0的规格
    let specList = productForm.specificationList.filter(item => item.children.length > 0)
    //因为列下标从0开始，而数组长度从1开始
    if (columnIndex < specList.length - 1) {
        let rowSpanNum = 1
        for (let index = columnIndex + 1; index < specList.length; index++) {
            rowSpanNum *= specList[index].children.length
        }
        if (rowIndex % rowSpanNum === 0) {
            return { rowspan: rowSpanNum, colspan: 1 }
        } else {
            return { rowspan: 0, colspan: 0 }
        }
    }
}
const submitSkuList = computed(() => {
    let arr = [] as ClassSku[]
    productForm.skuList.forEach(item => {
        arr.push(Object.assign({}, item))
    })
    arr.forEach(item => {
        item.price *= 100
        item.vipPrice *= 100
        item.originalPrice *= 100
    })
    return arr
})
/**
 * 最终提交
 */
const submitProductForm = async (formEl: FormInstance | undefined) => {
    //判断是否填写好sku列表信息
    let iserror = false

    productForm.skuList.forEach(item => {
        if (item.price == undefined || item.originalPrice == undefined || item.vipPrice == undefined || item.barCode == undefined || item.weight == undefined) {
            iserror = true
            return
        }
    })
    if (iserror) {
        return ElMessage.error('请填写好sku列表信息')
    }
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const { price, originalPrice, vipPrice } = productForm
            if (price && originalPrice && vipPrice && vipPrice <= price && price < originalPrice) {
                const data = {
                    _gp: 'admin.product', _mt: 'create', spuDTO: JSON.stringify({
                        ...productForm,
                        imgList: productForm.imgList.map((item: { response: { url: string } }) => item.response.url),
                        img: productForm.imgList.map((item: { response: { url: string } }) => item.response.url)[0],
                        skuList: submitSkuList.value
                    })
                }
                post(data).then(res => {
                    const { data, errno, errmsg } = res
                    if (200 == errno) {
                        dialogTableVisible.value = true
                    } else {
                        ElMessage.error(errmsg)
                    }
                })
            } else {
                ElMessage.error('价格格式应为：vip价<现价<原价')
            }
        } else {
            console.log('error submit!', fields)
            ElMessage.error('请检查信息是否填写完整')
        }
    })
}
/**
 * 删除tag标签
 */
const handleClose = (index: number, tagIndex: number) => {
    productForm.specificationList[index].children.splice(tagIndex, 1)
    createSkuTable()
}

const showInput = (index: number) => {
    productForm.specificationList[index].inputVisible = true
}
/**
 * 添加tag标签
 */
const handleInputConfirm = (index: number) => {
    if (inputValue.value) {
        let bol = productForm.specificationList[index].children.includes(inputValue.value)
        if (!bol) {
            productForm.specificationList[index].children.push(inputValue.value)
            createSkuTable()
        } else {
            ElMessage.error("该规格已存在")
        }
    }
    productForm.specificationList[index].inputVisible = false
    inputValue.value = ''
}
/**
 * 关闭创建页面，跳到商品列表
 */
function handleGoProduct() {
    useTagsStore().removeTagByPath(router.currentRoute.value.fullPath)
    router.push('/index/productmanage/productlist')
}
/**
 * 继续创建
 */
function handleContinueCreate() {
    initObj(productForm)
    dialogTableVisible.value = false
}
</script>
<style lang="less" scoped>
.tag {
    margin: 10px 0;

    &>:deep(.el-input) {
        width: 100px;
    }

    &>:deep(.el-tag) {
        margin-right: 10px;
    }
}

.saveBtn {
    display: flex;
    justify-content: end;
    margin-top: 10px;
}
</style>